angular.module('user', []).controller('userCtrl', [ '$scope', '$http', function($scope, $http) {

	//$scope.viewmode = true;
	$scope.roles = ["ADMIN","USER"];
    $scope.viewmode = [];
	$scope.newUser = {
		"email": "",
		"password": "",
		"role":$scope.roles[1]
	};
    $scope.userList = [];
	/*userService.getList().success(function(){
		console.log("user list has been loaded");
	});*/
    $http.get('/api/users').success(function(data){
        $scope.userList = data;
        for (var i = 0; i < $scope.userList.length; i++){
            $scope.viewmode[$scope.userList[i]._id] = true;
        }
		console.log("user list has been loaded");
	});
	
	$scope.addUser = function(){
		$http.post('/api/user/add', $scope.newUser).success(function(data){
			console.log("New user has been created");
            $scope.userList = $scope.userList.concat(data);
            $scope.viewmode[data[0]._id] = true;
		});
	};

    $scope.deleteUser = function(user){
        var index = $scope.userList.indexOf(user);
        $http.post('/api/user/delete', user).success(function(data){
            console.log("A user has been deleted");
            $scope.userList.splice(index, 1);
        });
    };

    $scope.editUser = function(user){
        $scope.viewmode[user._id] = false;
    }
    $scope.saveUser = function(user){
        $http.post('/api/user/update', user).success(function(data){
            console.log("A user has been updated");
            console.log(data);
            $scope.viewmode[user._id] = true;
        });
    }
}]);